import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:go_router/go_router.dart';

import '../../core/models/user_model.dart';
import '../../core/providers/follow_provider.dart';
import '../../core/providers/user_provider.dart';

class SocialConnectionScreen extends ConsumerStatefulWidget {
  final String pageType;

  const SocialConnectionScreen({super.key, required this.pageType});

  @override
  ConsumerState<SocialConnectionScreen> createState() =>
      _SocialConnectionScreenState();
}

class _SocialConnectionScreenState
    extends ConsumerState<SocialConnectionScreen> {
  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);
    if (currentUser == null) {
      return Scaffold(
        body: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/resources/common_bg_2.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: SafeArea(
            child:
                [
                  _buildTopNavigationBar(),
                  SizedBox(height: 100.h),
                  [
                    Icon(
                      Icons.person_outline,
                      size: 80.sp,
                      color: Colors.grey[400],
                    ),
                    SizedBox(height: 20.h),
                    Text(
                      'Please login first',
                      style: TextStyle(
                        fontSize: 18.sp,
                        color: Colors.grey[600],
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      'Login to see your connections',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[500],
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ].toColumn(mainAxisAlignment: MainAxisAlignment.center),
                ].toColumn(),
          ),
        ),
      );
    }

    final userIds =
        widget.pageType == 'following'
            ? ref.watch(userFollowingListProvider(currentUser.id))
            : ref.watch(userFollowersListProvider(currentUser.id));

    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();

    final users =
        userIds
            .map(
              (id) => allUsers.firstWhere(
                (user) => user.id == id,
                orElse: () => UserDataEntity.empty(),
              ),
            )
            .where((user) => user.isValid)
            .toList();

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [
                _buildTopNavigationBar(),
                SizedBox(height: 20.h),
                Expanded(
                  child:
                      users.isEmpty
                          ? _buildEmptyState()
                          : _buildUsersGrid(users, currentUser),
                ),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: [
        Container(
          width: 30.w,
          height: 30.h,
          decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Icon(
            Icons.arrow_back_ios_new,
            color: Colors.white,
            size: 20.sp,
          ),
        ).inkWell(onTap: () => Navigator.of(context).pop()),
        Text(
          widget.pageType == 'following' ? 'Follow' : 'Fan',
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
        ),
        SizedBox(width: 40.w),
      ].toRow(mainAxisAlignment: MainAxisAlignment.spaceBetween),
    );
  }

  Widget _buildEmptyState() {
    final isFollowing = widget.pageType == 'following';
    return [
      SizedBox(height: 100.h),
      Icon(
        isFollowing ? Icons.person_add_outlined : Icons.people_outline,
        size: 80.sp,
        color: Colors.grey[400],
      ),
      SizedBox(height: 20.h),
      Text(
        isFollowing ? 'No following yet' : 'No fans yet',
        style: TextStyle(
          fontSize: 18.sp,
          color: Colors.grey[600],
          fontWeight: FontWeight.w500,
        ),
      ),
      SizedBox(height: 8.h),
      Text(
        isFollowing
            ? 'Start following people you\'re interested in!'
            : 'Share great content to attract fans!',
        style: TextStyle(fontSize: 14.sp, color: Colors.grey[500]),
        textAlign: TextAlign.center,
      ),
    ].toColumn(mainAxisAlignment: MainAxisAlignment.center);
  }

  Widget _buildUsersGrid(
    List<UserDataEntity> users,
    UserDataEntity currentUser,
  ) {
    return Container(
      margin: EdgeInsets.only(top: 40.h),
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 0.w,
          mainAxisSpacing: 30.h,
          childAspectRatio: 118 / 132,
        ),
        itemCount: users.length,
        itemBuilder: (context, index) {
          final user = users[index];
          return _buildUserItem(user, currentUser);
        },
      ),
    );
  }

  Widget _buildUserItem(UserDataEntity user, UserDataEntity currentUser) {
    final isFollowing = ref.watch(
      isFollowingProvider({
        'followerId': currentUser.id,
        'followeeId': user.id,
      }),
    );

    return Stack(
      clipBehavior: Clip.none,
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(12.r),
          child: Stack(
            children: [
              AspectRatio(
                aspectRatio: 118 / 132,
                child: Image.asset(
                  'assets/resources/follow_bg.png',
                  fit: BoxFit.fill,
                  width: double.infinity,
                ),
              ),
              Positioned.fill(
                child: [
                  SizedBox(height: 40.h),
                  Text(
                    user.username,
                    style: TextStyle(
                      fontSize: 17.sp,
                      color: Colors.black87,
                      fontWeight: FontWeight.w600,
                      fontFamily: 'PoetsenOne',
                    ),
                    textAlign: TextAlign.center,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 8.h),
                  Container(
                    width: 96.w,
                    height: 36.h,
                    decoration: BoxDecoration(
                      color: isFollowing ? Colors.grey[300] : Color(0xFFFDDB31),
                      borderRadius: BorderRadius.circular(23.r),
                    ),
                    child: Center(
                      child: Text(
                        isFollowing ? 'Following' : '+Follow',
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: isFollowing ? Colors.grey[700] : Colors.white,
                          fontWeight: FontWeight.w600,
                          fontFamily: 'PoetsenOne',
                        ),
                      ),
                    ),
                  ).inkWell(
                    onTap:
                        () => _handleFollowTap(user, currentUser, isFollowing),
                  ),
                  SizedBox(height: 12.h),
                ].toColumn(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                ),
              ),
            ],
          ),
        ),
        Positioned(
          top: -26.h,
          left: 0,
          right: 0,
          child: Center(
            child: Container(
              width: 68.w,
              height: 68.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.black, width: 1.w),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.1),
                    blurRadius: 8.r,
                    offset: Offset(0, 2.h),
                  ),
                ],
              ),
              child: ClipOval(
                child: Image.asset(user.avatar, fit: BoxFit.cover),
              ),
            ).inkWell(
              onTap: () {
                GoRouter.of(context).push('/other-user-profile/${user.id}');
              },
            ),
          ),
        ),
      ],
    );
  }

  void _handleFollowTap(
    UserDataEntity user,
    UserDataEntity currentUser,
    bool isFollowing,
  ) async {
    final followNotifier = ref.read(userFollowProvider.notifier);

    if (isFollowing) {
      await followNotifier.unfollowUser(
        followerId: currentUser.id,
        followeeId: user.id,
      );
    } else {
      await followNotifier.followUser(
        followerId: currentUser.id,
        followeeId: user.id,
      );
    }
  }
}
